package com.xiaoq.matrix.minipro.endpoint;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.xiaoq.RedisTemplate4JedisCluster;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.ConstantUtil;
import com.xiaoq.matrix.minipro.service.impl.MiniProQlCodeServiceImpl;
import com.xiaoq.matrix.minipro.service.impl.MiniProServiceImpl;
import com.xiaoq.matrix.minipro.service.impl.WxOpenServiceDemo;
import com.xiaoq.matrix.minipro.vo.MiniProAuditStatusResponse;
import com.xiaoq.matrix.minipro.vo.MiniProBaseResponse;
import com.xiaoq.matrix.minipro.vo.MiniProDetailInfoVo;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@RestController
@RequestMapping("/api/v1/minipmgr")
public class MiniProMgrEndpoint {
private static final Logger LOG = LoggerFactory.getLogger(MiniProMgrEndpoint.class);
	
	private class MiniProDetailResponse extends GenericDataResponse<MiniProDetailInfoVo> {}
	@Autowired
	private  MiniProServiceImpl miniProService;
	
	@Autowired
    protected WxOpenServiceDemo wxOpenServiceDemo;
	
	@Autowired
	private RedisTemplate4JedisCluster redisTemplate;

	@ApiOperation(value = "获取小程序上线二维码", notes = "获取小程序上线二维码")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "获取小程序上线二维码") })
	@GetMapping(value = "/minicode", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> getQlCode(HttpServletRequest request,@RequestParam(value="path",required=true)@ApiParam(value="小程序对应的路径")String path){
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		if("pages/index/index".equals(path)){
			String qrImage = miniProService.getShopMiniProQrImage(shopId, "2");
			return GenericDataResponse.okWithData(qrImage);
		}
		String accessToken = miniProService.getAccessTokenByShopId(shopId, "2");
		String base64QlCode = MiniProQlCodeServiceImpl.getminiqrQr(accessToken,path);
		miniProService.updateQrImage(shopId, "2", base64QlCode);
		return GenericDataResponse.okWithData(base64QlCode);
		
		
	}
	
	@ApiOperation(value = "添加体验二维码的体验者", notes = "添加体验二维码的体验者")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "添加体验二维码的体验者") })
	@PostMapping(value = "/axperiencers", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> addExperiencer(
			@RequestParam(value="wechatid",required=true)@ApiParam(value="体验者微信号")String wechatid,
			HttpServletRequest request){
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		String accessToken = miniProService.getAccessTokenByShopId(shopId, "2");
		MiniProBaseResponse miniPro = miniProService.addExperiencer(accessToken,wechatid);
		return GenericDataResponse.okWithData(miniPro);
		
		
	}
	

	@ApiOperation(value = "获取体验二维码(全网发布之前添加体验者才可以扫二维码体验)", notes = "获取体验二维码")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "获取体验二维码") })
	@GetMapping(value = "/qrCode", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> getQRCode(HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		String accessToken = miniProService.getAccessTokenByShopId(shopId, "2");
		String miniPro = miniProService.getQRCodeFromWeixin(accessToken);
		return GenericDataResponse.okWithData(miniPro);

	}
	
	
	@ApiOperation(value = "发布小程序", notes = "发布小程序")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericDataResponse.class, message = "跳转链接")})
	@PostMapping(value = "/audit/{appId}")
	public ResponseEntity<?> submitAudit(HttpServletRequest req, @PathVariable String appId) {
		String userId = (String) req.getAttribute("userId");
		LOG.info("用户" + userId + "发布小程序");
		miniProService.audit(userId, appId);
		return GenericDataResponse.ok();
	}
	
	// 如果返回内容为空，说明还没有绑定小程序
	@ApiOperation(value = "查询小程序状态", notes = "查询小程序状态")
	@ApiResponses({ @ApiResponse(code = 200, response = MiniProDetailResponse.class, message = "跳转链接")})
	@GetMapping(value = "/detail/{shopId}")
	public ResponseEntity<?> getMiniProDetail(HttpServletRequest req, @PathVariable String shopId) {
		String userId = (String) req.getAttribute("userId");
		MiniProDetailInfoVo detail = miniProService.getMiniProDetail(userId, shopId);
		return GenericDataResponse.okWithData(detail);
	}
	
	@ApiOperation(value = "查询用户最新一次的审核状态", notes = "查询用户最新一次的审核状态")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "查询用户最新一次的审核状态") })
	@PostMapping(value = "/lastStatus", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> getLastAuditStatusFromWeixin(HttpServletRequest request){
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		String accessToken = miniProService.getAccessTokenByShopId(shopId, "2");
		MiniProAuditStatusResponse miniPro = miniProService.getLastAuditStatusFromWeixin(accessToken);
		return GenericDataResponse.okWithData(miniPro);
		
		
	}
	
	@ApiOperation(value = "添加商户号和商户秘钥（认证完成后才能晚上商户号和商户秘钥）", notes = "添加商户号和商户秘钥")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "添加商户号和商户秘钥") })
	@PostMapping(value = "/secrets", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> addMiniProSecret(@RequestParam String appId,@RequestParam String appSecret){
		boolean result = miniProService.addSecret(appId, appSecret);
		if(result){
			return GenericResponse.ok();
		}
		return GenericDataResponse.ng("小程序认证后才能添加商户号！");
		
		
	}
}
